package com.wiloon.java.network.network.nettyhttpserver.nettyhttpclient;

/**
 * Created by Roy on 2015/12/17;
 */


import com.wiloon.java.network.network.nettyhttpserver.monitor.RequestCounter;
import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.URI;

public class HttpClient {
    private final static Logger logger = LoggerFactory.getLogger(HttpClient.class);
    Bootstrap bootstrap;
    DefaultFullHttpRequest request;
    Channel channel;

    public HttpClient(EventLoopGroup workerGroup) {
        bootstrap = new Bootstrap();
        bootstrap.group(workerGroup);
        bootstrap.channel(NioSocketChannel.class);
        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);
        bootstrap.handler(new ChannelInitializer<SocketChannel>() {
            @Override
            public void initChannel(SocketChannel ch) throws Exception {
                // 客户端接收到的是httpResponse响应，所以要使用HttpResponseDecoder进行解码
                ch.pipeline().addLast(new HttpResponseDecoder());
                // 客户端发送的是httprequest，所以要使用HttpRequestEncoder进行编码
                ch.pipeline().addLast(new HttpRequestEncoder());
                ch.pipeline().addLast(new HttpClientHandler(false));
            }
        });
    }

    public void connect(String host, int port, String url) throws Exception {


        try {
            // Start the client.
            ChannelFuture f = bootstrap.connect(host, port).sync();

            URI uri = new URI(url);
            String msg = "";
            request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.GET,
                    uri.toASCIIString(), Unpooled.wrappedBuffer(msg.getBytes("UTF-8")));

            // 构建http请求
            request.headers().set(HttpHeaders.Names.HOST, host);
            request.headers().set(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE);
            request.headers().set(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(request.content().readableBytes()));

            //  while (true) {

            // 发送http请求
            channel = f.channel();
            // logger.trace("send channel:{}", channel);

            //  Thread.sleep(1);
            //  }


        } finally {
            //workerGroup.shutdownGracefully();

        }
    }

    public void sendRequest() {
        RequestCounter.count();
        channel.writeAndFlush(request);
    }

    public void sync() {
        try {
            //channel.closeFuture().sync();
            Thread.sleep(1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}